package com.jiaoyou.demo.Controller;


import com.jiaoyou.demo.entity.Good;
import com.jiaoyou.demo.service.GoodService;
import com.jiaoyou.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/goods")
public class queryController {
    @Autowired
    private GoodService goodService;

    @Autowired
    private UserService userService;
    @RequestMapping("/query")           //通过关键字查询商品
    public Object goods(
            @RequestParam("query")String query,
            @RequestParam("pagenum")int page,
            @RequestParam("classid")int id) //这里分类id还没实现
    {
        int i=(page-1)*20;
        List<Good> goods = goodService.queryGoods(query,i,20);
        return new JsonResult(goods);
    }
    @RequestMapping("/detail")          //商品信息
    public Object detail(@RequestParam("goods_id")int goods_id){
        Good good = goodService.queryById(goods_id);
        return new JsonResult(good);
    }
    @RequestMapping("/buy")             //购买商品
    public Object buy(@RequestParam("goods_id")int goods_id,@RequestParam("user_id")int user_id){
        Good good = goodService.queryById(goods_id);
        if(user_id==good.getUserId()){
            return new JsonResult("不能购买自己的商品哦");
        }
        /*更新数据库，并返回购买者的QQ号*/
        good.setPurchaser(user_id);
        goodService.update(good);
        return new JsonResult(userService.queryById(user_id).getQq());
    }
    @RequestMapping("/confirm")         //确认收货
    public Object confirm(@RequestParam("goods_id")int goods_id,@RequestParam("user_id")int user_id){
        Good good = goodService.queryById(goods_id);
        if(user_id==good.getPurchaser()){//验证当前用户是否为购买者
        good.setSold(true);             //已卖出
        goodService.update(good);
        return new JsonResult();
        }else {
            String error="非购买者";
            return new JsonResult(error);
        }
    }

}
